//
//  UUChatViewController.m
//  家校互通
//
//  Created by 李赛 on 15/7/9.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "UUChatViewController.h"
#import "UUInputFunctionView.h"
#import "MJRefresh.h"
#import "UUMessageCell.h"
#import "ChatModel.h"
#import "UUMessageFrame.h"
#import "UUMessage.h"
#import "CoModel.h"
#import "TalkModel.h"
#import "APService.h"
#import "CreateAChatViewController.h"

#import "DSFMovieDetailFFMDBModel.h"
@interface UUChatViewController ()<UUInputFunctionViewDelegate,UUMessageCellDelegate,UITableViewDataSource,UITableViewDelegate,ConnectControlDelegate>
{
    UUInputFunctionView *IFView;
    ConnectControl *connectCtr;
}


@property (strong, nonatomic) ChatModel *chatModel;
@property (nonatomic, strong) ChartDetail *chartDetail;
@property (weak, nonatomic) IBOutlet UITableView *chatTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@end

@implementation UUChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _chatTableView.delegate=self;
    _chatTableView.dataSource=self;
//    [self initBar];
       self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setTitle:@"成员" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(SegerToCreateAChatViewController:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:button];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kReciveSendImg object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kReciveSendMsg object:nil];

    
    [self addRefreshViews];
    connectCtr = [ConnectControl showForView:self.view];
    connectCtr.delegate=self;
    
    if (connectCtr.superview!=nil && connectCtr.loading==NO)
    {
        [connectCtr setLoading:YES];
    }
//    [self loadBaseViewsAndData];
}
-(void)SegerToCreateAChatViewController:(UIButton *)sender
{
    CreateAChatViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"CreateAChatViewController"];
    vc.chartId=_chartId;
    vc.title=self.title;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)connect{
    [CoModel getChartDetail:^(BOOL result, ChartDetail *model,NSError *error) {
        _chartDetail = model;
        [CoModel getMessages:^(BOOL result, NSArray *msgList, NSError *error) {
            [ConnectControl removeFromView:self.view];
            self.chatModel = [[ChatModel alloc]init];
            self.chatModel.isGroupChat = NO;
            self.chatModel.dataSource = [NSMutableArray array];
            
            for (TalkMessage *talk in msgList) {
                [self.chatModel.dataSource addObject:[self talkMessageToUUMessageFram:talk]];
            }
            
            //储存消息数
            [[DSFMovieDetailFFMDBModel sharedSingleton] insertHistory:_chartId chartCount:self.chatModel.dataSource.count];
            
            [self loadBaseViewsAndData];
        } withChartId:_chartId];
    } withChartId:_chartId];
}

static NSString *previousTime = nil;
- (UUMessageFrame *)talkMessageToUUMessageFram:(TalkMessage *)talk{
    UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
    UUMessage *message = [[UUMessage alloc] init];
    [message setWithDict:talk andChart:_chartDetail];
//    [message setWithDict:dataDic];
    [message minuteOffSetStart:previousTime end:talk.msg_time];
    messageFrame.showTime = message.showDateLabel;
    [messageFrame setMessage:message];
    if (message.showDateLabel) {
        previousTime = talk.msg_time;
    }
    return messageFrame;
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //add notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tableViewScrollToBottom) name:UIKeyboardDidShowNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadNewsList object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)initBar
{
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@" private ",@" group "]];
    [segment addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
    segment.selectedSegmentIndex = 0;
    self.navigationItem.titleView = segment;
    
//    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:nil action:nil];

}
- (void)segmentChanged:(UISegmentedControl *)segment
{
    self.chatModel.isGroupChat = segment.selectedSegmentIndex;
    [self.chatModel.dataSource removeAllObjects];
    [self.chatModel populateRandomDataSource];
    [self.chatTableView reloadData];
}

-(void)addFooter
{
    self.chatTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    }];
}
- (void)addRefreshViews
{
    //load more
    int pageNum = 10;
    
    __weak __typeof(self) weakSelf = self;
     [self.chatTableView.header beginRefreshing];
    self.chatTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    
//        [weakSelf.chatModel addRandomItemsToDataSource:pageNum];
        
        if (weakSelf.chatModel.dataSource.count > pageNum) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.chatTableView reloadData];
                [weakSelf.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            });
        }
        [weakSelf.chatTableView.header endRefreshing];

    }];

}

- (void)loadBaseViewsAndData
{
//    self.chatModel = [[ChatModel alloc]init];
//    self.chatModel.isGroupChat = NO;
//    [self.chatModel populateRandomDataSource];
    
    IFView = [[UUInputFunctionView alloc]initWithSuperVC:self];
    IFView.delegate = self;
    [self.view addSubview:IFView];
    
    [self.chatTableView reloadData];
    [self tableViewScrollToBottom];
}

-(void)keyboardChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    //adjust ChatTableView's height
    if (notification.name == UIKeyboardWillShowNotification) {
        self.bottomConstraint.constant = keyboardEndFrame.size.height+40;
    }else{
        self.bottomConstraint.constant = 40;
    }
    
    [self.view layoutIfNeeded];
    
    //adjust UUInputFunctionView's originPoint
    CGRect newFrame = IFView.frame;
    newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;
    IFView.frame = newFrame;
    
    [UIView commitAnimations];
    
}

//tableView Scroll to bottom
- (void)tableViewScrollToBottom
{
    if (self.chatModel.dataSource.count==0)
        return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.dataSource.count-1 inSection:0];
    [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


#pragma mark - InputFunctionViewDelegate
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message
{
    NSDictionary *dic = @{@"strContent": message,
                          @"type": @(UUMessageTypeText)};
    funcView.TextViewInput.text = @"";
    [funcView changeSendBtnWithPhoto:YES];
    [self dealTheFunctionData:dic];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image
{
    NSDictionary *dic = @{@"picture": image,
                          @"type": @(UUMessageTypePicture)};
    [self dealTheFunctionDataImage:dic];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second
{
    NSDictionary *dic = @{@"voice": voice,
                          @"strVoiceTime": [NSString stringWithFormat:@"%d",(int)second],
                          @"type": @(UUMessageTypeVoice)};
    [self dealTheFunctionData:dic];
}


#pragma mark -发送接收消息

//发送消息
- (void)dealTheFunctionData:(NSDictionary *)dic
{
    [TalkModel sendMsg:^(BOOL result, NSError *error) {
        if (result) {
            [self.chatModel addSpecifiedItem:dic];
            [self.chatTableView reloadData];
            [self tableViewScrollToBottom];
            
            //储存消息数
            [[DSFMovieDetailFFMDBModel sharedSingleton] insertHistory:_chartId chartCount:self.chatModel.dataSource.count];
        }
    } andChartId:_chartId andReceiverId:0 andContent:dic[@"strContent"]];
}

//发送图片消息
- (void)dealTheFunctionDataImage:(NSDictionary *)dic{
    NSArray *imageArr = [NSArray arrayWithObjects:dic[@"picture"], nil];
    
    [CoModel uploadImage:^(BOOL result, NSMutableArray *imageUrlList, NSError *error) {
        NSString *string = imageUrlList[0];
        [TalkModel sendImg:^(BOOL result, NSError *error) {
            if (result) {
                [self.chatModel addSpecifiedItem:dic];
                [self.chatTableView reloadData];
                [self tableViewScrollToBottom];
                
                //储存消息数
                [[DSFMovieDetailFFMDBModel sharedSingleton] insertHistory:_chartId chartCount:self.chatModel.dataSource.count];
            }
        } andChartId:_chartId andReceiverId:0 andContent:string];
    } withImage:imageArr andType:3];
}


//收到消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];

    TalkMessage *talk = [[TalkMessage alloc] initWithDictionary:[userInfo objectForKey:@"data"] error:nil];
    
    if (talk.chart_id == _chartId) {
        [self.chatModel.dataSource addObject:[self talkMessageToUUMessageFram:talk]];
        [self.chatTableView reloadData];
        [self tableViewScrollToBottom];
        
        //储存消息数
        [[DSFMovieDetailFFMDBModel sharedSingleton] insertHistory:_chartId chartCount:self.chatModel.dataSource.count];
    }
}
#pragma mark - tableView delegate & datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UUMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (cell == nil) {
        cell = [[UUMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
        cell.delegate = self;
    }
    [cell setMessageFrame:self.chatModel.dataSource[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.chatModel.dataSource[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - cellDelegate
- (void)headImageDidClick:(UUMessageCell *)cell userId:(NSString *)userId{
    // headIamgeIcon is clicked
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:cell.messageFrame.message.strName message:@"headImage clicked" delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
    [alert show];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
